package com.org.oracle.controller;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.org.oracle.mongodb.dto.DeepSeekChatDTO;
import com.org.oracle.mongodb.dto.DeepSeekDirectRequestDTO;
import com.org.oracle.mongodb.entity.DeepSeekChatRecord;
import com.org.oracle.mongodb.vo.TempDeepSeekNewChatVO;
import com.org.oracle.result.Result;
import com.org.oracle.service.DeepSeekChatService;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@RestController
@RequestMapping("/deepseek")
public class ApiAIController {
    ChatClient chatClient;
    private final DashScopeChatModel chatModel;
    @Resource
    private DeepSeekChatService chatService;


    public ApiAIController(ChatClient.Builder chatClientBuilder, DashScopeChatModel chatModel){
        this.chatClient = chatClientBuilder.build();
        this.chatModel = chatModel;
    }

    @CrossOrigin
    @GetMapping(value = "/testChat01")
    public String testChat(@RequestParam(value = "message", defaultValue = "你是谁？你是哪一家公司开发的？") String message){
        String content = chatClient.prompt()
                .system(s -> s.param("current_date", LocalDate.now().toString()))
                .user(message)
                .call()
                .content();
        return content;
    }
    @CrossOrigin
    @GetMapping(value = "/generateStreamAsString", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> generateStreamAsString(@RequestParam(value = "message", defaultValue = "讲个笑话") String message) {
        //Prompt prompt = new Prompt(new UserMessage(message));
        //return chatClient.stream(prompt);
        Flux<String> content = chatClient.prompt()
                .system(s -> s.param("current_date", LocalDate.now().toString()))
                //.advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId).param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100))
                .advisors(a -> a.param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100))
                .user(message)
                .stream()
                .content();

        return  content
                .concatWith(Flux.just("[complete]"));

    }
//    @PostMapping("/chat")
//    public Mono<ResponseEntity<Result>> completeChat(
//            @RequestParam String uid,
//            @RequestParam String message) {
//        return chatService.completeChat(uid, message)
//                .map(aiResponse -> ResponseEntity.ok(Result.ok(aiResponse)))
//                .onErrorResume(e -> Mono.just(ResponseEntity.ok(Result.fail("服务异常: " + e.getMessage()))));
//    }
    @PostMapping("/chat")
    public Mono<ResponseEntity<Result>> completeChat(
            @RequestBody DeepSeekChatDTO request) { // 使用 @RequestBody
        return chatService.completeChat(request.getUid(), request.getMessage())
                .map(aiResponse -> ResponseEntity.ok(Result.ok(aiResponse)))
                .onErrorResume(e -> Mono.just(ResponseEntity.ok(Result.fail("服务异常: " + e.getMessage()))));
    }

    @PostMapping("/direct-chat")
    public Mono<TempDeepSeekNewChatVO> handleDirectChat(
            @RequestBody @Validated DeepSeekDirectRequestDTO request) {
        return chatService.processDirectRequest(request);
    }

//    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public Flux<ServerSentEvent<String>> streamChat(
//            @RequestParam String userId,
//            @RequestParam String message) {
//        return chatService.streamChat(userId, message)
//                .map(content -> ServerSentEvent.builder(content).build())
//                .onErrorResume(e -> Flux.just(
//                        ServerSentEvent.builder("服务异常: " + e.getMessage()).build()
//                ));
//    }

//    @GetMapping("/chat")
//    public Mono<ResponseEntity<Result>> completeChat(
//            @RequestParam String userId,
//            @RequestParam String message) {
//        return chatService.completeChat(userId, message)
//                .map(aiResponse -> ResponseEntity.ok(Result.ok(aiResponse)))
//                .onErrorResume(e -> Mono.just(ResponseEntity.ok(Result.fail("服务异常: " + e.getMessage()))));
//    }
//
//    @GetMapping("/history")
//    public Result getHistory(
//            @RequestParam String userId) {
//        return Result.ok(chatService.getChatHistory(userId));
//    }
//    @GetMapping("/test/{prompt}")
//    public String chat(@PathVariable(value = "prompt") String prompt) {
//
//        ChatResponse chatResponse = chatModel.call(new Prompt("你好！"));
//
//        if (!chatResponse.getResults().isEmpty()) {
//            Map<String, Object> metadata = chatResponse.getResults()
//                    .get(0)
//                    .getOutput()
//                    .getMetadata();
//
//            System.out.println(metadata.get("reasoningContent"));
//        }
//
//        return chatResponse.getResult().getOutput().getContent();
//    }
}